import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/entity/home/news_item_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/local_read_history.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';

import '../../widgets/base/qkd_text.dart';

class NewsItemCell extends StatelessWidget {
  final NewsItemEntity e;
  final int? classId;
  final bool inHome;
  final int? imgStyle;
  final void Function()? afterRoute;
  final bool bottomDivider;
  final bool isSubscribe;
  final String? id;
  final Function()? onTap;

  const NewsItemCell(this.e,
      {super.key,
      this.classId,
      this.inHome = true,
      this.imgStyle,
      this.afterRoute,
      this.bottomDivider = true,
      this.isSubscribe = false,
      this.id,
      this.onTap});

  @override
  Widget build(BuildContext context) {
    return _cell();
  }

  _cell() {
    // final c = _cell3(e);
    late Widget c;
    final style = imgStyle ?? e.imgStyle ?? 1;
    if (style == 1) {
      c = _cell1(e);
    } else if (style == 2) {
      c = _cell2(e);
    } else {
      c = _cell3(e);
    }

    return GestureDetector(
      onTap: () {
        if (isSubscribe) {
          Get.toNamed(Routes.subscribeArticle, arguments: e.id);
          return;
        }
        int? classId = this.classId;
        Utils.onEvent("home_article", params: {"article_id": e.id, "channel": id});
        if (e.imgStyle == 4) {
          Get.toNamed(Routes.homeVideoNews,
              arguments: e.id,
              parameters: {'classId': "$classId"})?.then((value) {
            afterRoute?.call();
          });
        } else {
          // Get.to(NewsView(data: e));
          Get.toNamed(Routes.homenews,
                  arguments: e.id,
                  parameters: {'classId': "$classId", "id": id??""},
                  preventDuplicates: false)
              ?.then((value) {
            afterRoute?.call();
          });
        }
      },
      behavior: HitTestBehavior.opaque,
      child: Container(
        clipBehavior: Clip.hardEdge,
        decoration: BoxDecoration(
            color: Colours.white, borderRadius: BorderRadius.circular(8)),
        child: c.paddingSymmetric(horizontal: 12, vertical: 12),
      ).marginOnly(left: 8, right: 8, top: 8),
    );
  }

  Widget _title(NewsItemEntity e) {
    final readed =
        e.isRead == 1 ? true : LocalReadHistory.hasReadedNews("${e.id}");
    final color = readed ? Colours.grey99 : Colours.text;
    return Text.rich(
      TextSpan(children: [
        if ((e.top ?? 0) >= 1 && inHome)
          WidgetSpan(
            alignment: PlaceholderAlignment.middle,
            child: Image.asset(Utils.getImgPath("pin_top.png"),width: 16)
          ),
        TextSpan(
          text: e.title ?? "",
          style: TextStyle(
              fontSize: 17,
              fontWeight: FontWeight.normal,
              color: color,
              height: 1.3),
        ).formHighLight()
      ]),
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
      textAlign: TextAlign.left,
    ).marginOnly(bottom: 8);
  }

  Widget _bottomRow(NewsItemEntity e) {
    final l = [
      e.publisherName?.trim(),
      e.pv?.trim(),
      if (inHome) e.publishTime?.trim()
    ];
    l.removeWhere((element) => element?.isEmpty ?? true);
    return DefaultTextStyle(
      maxLines: 1,
      style: const TextStyle(fontSize: 11, color: Colours.grey99),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.baseline,
        textBaseline: TextBaseline.alphabetic,
        children: [
          QkdText(e.publisherName?.trim() ?? ''),
          if (inHome) QkdText('  ${e.publishTime?.trim() ?? ''}'),
          const Spacer(),
          if(e.commentNum.hasValue)
          QkdText("评论${e.commentNum}" ?? '').paddingOnly(right: 8),
          QkdText(e.pv?.trim() ?? ''),
        ],
      ),
    );
  }

  //无图
  _cell1(NewsItemEntity e) {
    return SizedBox(
      child: Row(
        children: [
          Expanded(
              child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _title(e),
              // QkdText(
              //     "${e.publicerName != null ? "${e.publicerName?.trim()}\u0020\u0020" : ""}"
              //     "${e.pv != null ? "${e.pv?.trim()}\u0020\u0020" : ""}"
              //     "${e.publicTime != null ? "${e.publicTime?.trim()}" : ""}",
              //     style:
              //         const TextStyle(fontSize: 11, color: Colours.grey_color1))
              _bottomRow(e)
            ],
          )),
        ],
      ),
    );
  }

  //右图
  _cell2(NewsItemEntity e) {
    return Container(
      height: 70,
      // padding: EdgeInsets.symmetric(vertical: 12),
      child: Row(
        children: [
          Expanded(
              child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(child: _title(e)),
              // QkdText(
              //   "${e.publicerName != null ? "${e.publicerName?.trim()}\u0020\u0020" : ""}"
              //   "${e.pv != null ? "${e.pv?.trim()}\u0020\u0020" : ""}"
              //   "${e.publicTime != null ? "${e.publicTime?.trim()}" : ""}",
              //   style:
              //       const TextStyle(fontSize: 11, color: Colours.grey_color1),
              // ),
              _bottomRow(e)
            ],
          )),
          Container(
            decoration: BoxDecoration(borderRadius: BorderRadius.circular(4)),
            clipBehavior: Clip.hardEdge,
            margin: const EdgeInsets.only(left: 12),
            width: 114,
            height: 71,
            child: CachedNetworkImage(
              imageUrl: e.imgs ?? "",
              fit: BoxFit.cover,
              errorWidget: (context, url, error) =>
                  Container(color: Colors.white),
              placeholder: ((context, url) => Container(color: Colors.white)),
            )
          ),
        ],
      ),
    );
  }

  //大图
  _cell3(NewsItemEntity e) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _title(e),
        Stack(
          alignment: Alignment.center,
          children: [
            Container(
              decoration:
                  BoxDecoration(borderRadius: BorderRadius.circular(10)),
              clipBehavior: Clip.hardEdge,
              child: AspectRatio(
                  aspectRatio: 343 / 146,
                  child: CachedNetworkImage(
                      imageUrl: e.imgs ?? "",
                      fit: BoxFit.cover,
                      errorWidget: (context, url, error) =>
                          Container(color: Colors.white),
                      placeholder: ((context, url) =>
                          Container(color: Colors.white)))),
            ),
            if (e.type == 3)
              Image.asset(Utils.getImgPath('home_video_play.png'), width: 50)
          ],
        ),

        const SizedBox(height: 10),
        // QkdText(
        //   "${e.publicerName != null ? "${e.publicerName?.trim()}\u0020\u0020" : ""}"
        //   "${e.pv != null ? "${e.pv?.trim()}\u0020\u0020" : ""}"
        //   "${e.publicTime != null ? "${e.publicTime?.trim()}" : ""}",
        //   style: const TextStyle(fontSize: 11, color: Colours.grey_color1),
        // )
        _bottomRow(e)
      ],
    );
  }
}
